var webim = require('../../resource/js/chat/webim.js');
var webimhandler = require('../../resource/js/chat/webim_handler.js');
var tls = require('../../resource/js/chat/tls.js');

var app = getApp();
Page({
    data: {
        siteInfo: app.siteInfo,
        bottom_scroll_top: 0,
        addShopCartLoading: 0,
        showlivecover: true,

        isLogin: 1,//是否登录有用户信息
        callMesg: '',
        isShowMesg: false,
        isShowGift: false,
        goodSelectIndex: -2,
        recommendGoods: {},
        goodsList: [],
        anchor: [],
        data: [],
        // 购物数量
        goodsNumber: 1,

        // 是否显示详情弹窗
        showDetailContainer: false,
        isShowBg: false,
        isShowShopCartList: false,
        isShowPayList: false,

        //规格参数
        selectSpecItems: {},
        selectGoodsItems: {},

        //聊天参数
        focus: false,
        playing: false,
        frontCamera: true,
        cameraContext: {},
        pushUrl: "",
        mode: "HD",
        muted: false,
        enableCamera: true,
        orientation: "vertical",
        beauty: 6.3,
        whiteness: 3.0,
        backgroundMute: false,
        hide: false,
        debug: false,
        live: {},
        motto: 'Hello World',
        userInfo: {},
        msgs: [],
        avChatRoomId: '',
        Identifier: '',
        UserSig: '',
        msgContent: "111",
        id: 0,
        //点赞
        likeList: [],
        likeTimer: null
    },

    onLoad: function () {
        var that = this;
        app.initPage({'navigationBarTitleText': ''});

        app.util.request({
            'url': 'index/siteInfo',
            'cachetime': '600',
            success: function (res) {
                var data = res.data.data;
                that.setData({
                    globalSiteInfo: data
                })
            }
        });

        let userInfo = wx.getStorageSync('userInfo');
        if (!userInfo || !userInfo.memberInfo.nickname) {
            that.setData({
                isLogin: 0,
            });
        }

        var id = that.options.id;

        that.setData({
            'live_id': id,
        });

        that.initShareData();
    },
    //获取用户信息
    updateUserInfo(result) {
        var that = this;
        app.util.getUserInfo(function (userInfo) {
            //更细本地userInfo
            app.util.request({
                url: 'user/synUser',
                data: {'uid': userInfo.memberInfo.uid},
                showLoading: false,
                header: {
                    contentType: "application/json",
                },
                method: 'POST',
                cachetime: 0,
                success: function (res) {
                    // wx.showToast({
                    //     title: '登录成功',
                    //     icon: 'none',
                    // });
                    that.setData({
                        isLogin: 1,
                    });
                    var memberInfo = userInfo.memberInfo;
                    that.setData({
                        userInfo: memberInfo,
                    });
                    that.requestInitIM(memberInfo);
                    //当前页面刷新
                    var page = getCurrentPages().pop();
                    page.onLoad();
                }
            });
        }, result.detail)
    },
    requestInitIM: function (userInfo) {
        var that = this;
        app.util.request({
            'url': 'live/getChatConfig',
            'cachetime': '60',
            success: function (res) {
                var data = res.data.data;
                that.setData({
                    'chat': data,
                });
                var Config = {
                    sdkappid: data.sdk_appid
                    , accountType: data.account_type
                    , accountMode: 1 //帐号模式，0-表示独立模式，1-表示托管模式
                };
                that.setData({
                    'avChatRoomId': data.room_id,
                    'Identifier': data.identifier,
                    'UserSig': data.user_sig,
                });
                tls.init({
                    sdkappid: data.sdk_appid
                })
                that.initIM(userInfo, Config);
            }
        });
    },
    logoutIM: function () {
        webimhandler.logout();
    },

    onReady: function () {
        wx.setKeepScreenOn({
            keepScreenOn: true,
        })
    },
    onShow: function () {
        var that = this;
        var id = that.options.id;
        app.util.getUserInfo(function (res) {
            var userInfo = res.memberInfo;
            that.setData({
                userInfo: userInfo,
            });
            if (userInfo && userInfo.nickname) {
                that.setData({
                    isLogin: 1,
                });
                that.requestInitIM(userInfo);
            }
            app.util.request({
                'url': 'live/detail',
                'data': {'id': id},
                success: function (res) {
                    var data = res.data.data;
                    //设置标题
                    wx.setNavigationBarTitle({
                        title: data.liveInfo.name,
                    });
                    that.setData({
                        'data': data,
                    });
                    that.setData({
                        'msgs': data.comment,
                    });
                }
            });
        });
        wx.createLivePlayerContext('live-player').play();//关闭
        //获取用户地址 更新
        app.util.request({
            'url': 'user/get_user_address',
            'showLoading': false,
            success: function (res) {
                var data = res.data.data;
                that.setData({
                    ['data.user.address']: data,
                });
            }
        });
        //保持屏幕常亮
        wx.setKeepScreenOn({
            keepScreenOn: true,
        })
    },
    onHide: function () {
        var that = this;
        wx.createLivePlayerContext('live-player').stop();//关闭
        that.logoutIM();
        //保持屏幕常亮
        wx.setKeepScreenOn({
            keepScreenOn: false,
        });
        app.util.request({
            'url': 'live/leave',
            'data': {'id': that.data.data.liveInfo.id},
            'showLoading': false,
            success: function (res) {
            }
        });
    },
    onUnload: function () {
        var that = this;
        wx.createLivePlayerContext('live-player').stop();//关闭
        webimhandler.logout();
        this.logoutIM();
        //保持屏幕常亮
        wx.setKeepScreenOn({
            keepScreenOn: false,
        });
        app.util.request({
            'url': 'live/leave',
            'data': {'id': that.data.data.liveInfo.id},
            'showLoading': false,
            success: function (res) {
            }
        });
    },
    sendMesg: function (res) {
        var that = this;
        var content = this.data.callMesg;
        if (!content.replace(/^\s*|\s*$/g, '')) return;
        that.setData({
            'isShowMesg': false,
        });
        this.setData({
            'bottom_scroll_top': this.data.bottom_scroll_top + 300,
        });
        webimhandler.onSendMsg(content, function () {
            //添加到评论
            that.setData({
                'callMesg': '',
            });
            app.util.request({
                'url': 'user/addComment',
                'showLoading': false,
                'data': {
                    'live_id': that.data.data.liveInfo.id,
                    'nickname': that.data.userInfo.nickname,
                    'type': 1,
                    'content': content
                },
                success: function (res) {
                }
            });
        })
    },
    //直播播放状态变更
    //学生一
    stufirlivestatechang:function(){
        var code = e.detail.code;
        if (code == 2004) {
            this.setData({
                'showlivecover': false,
            });
        }
    },
    //老师
    livestatechange: function (e) {
        var code = e.detail.code;
        if (code == 2004) {
            this.setData({
                'showlivecover': false,
            });
        }
    },
    followAnchor: function (e) {
        //关注
        var that = this;
        var anchor_id = e.target.dataset.anchor_id;
        var live_id = that.data.data.liveInfo.id;
        var data = that.data.data;
        app.util.request({
            'url': 'user/followAnchor',
            'showLoading': false,
            'data': {'anchor_id': anchor_id, 'live_id': live_id},
            success: function (res) {
                data.anchor.is_follow = res.data.data;
                //设置标题
                that.setData({
                    'data': data,
                });
            }
        });
    },



// 用户输入消息
    changeMesg: function (e) {
        var mesg = e.detail.value;
        this.setData({
            callMesg: mesg
        })
    },
//输入框失去焦点
    blurMesg: function () {
        this.setData({
            isShowMesg: false,
            chatInputFocus: 0,
        })
    },
    hideMesg: function () {
        this.setData({
            isShowMesg: false,
            chatInputFocus: 0,
        })
    },
    hideGift:function(){
        let isShowGift = this.data.isShowGift
        this.setData({
            isShowGift: !isShowGift,
        })
    },
    // 送礼物回调函数
    sendGift:function(e){
        this.hideGift()
        console.log(e.target.dataset.gift)
    },
    showGift:function(){
        let isShowGift = this.data.isShowGift
        this.setData({
            isShowGift: !isShowGift,
        })
    },
    showMesg: function () {
        this.setData({
            isShowMesg: true,
            chatInputFocus: 1,
        })
    },  
    initIM: function (userInfo, Config) {
        var that = this;
        var avChatRoomId = that.data.avChatRoomId;
        webimhandler.init({
            accountMode: Config.accountMode
            , accountType: Config.accountType
            , sdkAppID: Config.sdkappid
            , avChatRoomId: avChatRoomId //默认房间群ID，群类型必须是直播聊天室（AVChatRoom），这个为官方测试ID(托管模式)
            , selType: webim.SESSION_TYPE.GROUP
            , selToID: avChatRoomId
            , selSess: null //当前聊天会话
        });
        //当前用户身份
        var loginInfo = {
            'sdkAppID': Config.sdkappid, //用户所属应用id,必填
            'appIDAt3rd': Config.sdkappid, //用户所属应用id，必填
            'accountType': Config.accountType, //用户所属应用帐号类型，必填
            'identifier': that.data.Identifier, //当前用户ID,必须是否字符串类型，选填
            'identifierNick': userInfo.nickname, //当前用户昵称，选填
            'userSig': that.data.UserSig, //当前用户身份凭证，必须是字符串类型，选填
            'live_id': that.data.live_id, //直播间id
        };

        //监听（多终端同步）群系统消息方法，方法都定义在demo_group_notice.js文件中
        var onGroupSystemNotifys = {
            "5": webimhandler.onDestoryGroupNotify, //群被解散(全员接收)
            "11": webimhandler.onRevokeGroupNotify, //群已被回收(全员接收)
            "255": webimhandler.onCustomGroupNotify//用户自定义通知(默认全员接收)
        };

        //监听连接状态回调变化事件
        var onConnNotify = function (resp) {
            switch (resp.ErrorCode) {
                case webim.CONNECTION_STATUS.ON:
                    //webim.Log.warn('连接状态正常...');
                    break;
                case webim.CONNECTION_STATUS.OFF:
                    webim.Log.warn('连接已断开，无法收到新消息，请检查下你的网络是否正常');
                    break;
                default:
                    webim.Log.error('未知连接状态,status=' + resp.ErrorCode);
                    break;
            }
        };


        //监听事件
        var listeners = {
            "onConnNotify": webimhandler.onConnNotify, //选填
            "onBigGroupMsgNotify": function (msg) {
                webimhandler.onBigGroupMsgNotify(msg, function (msgs) {
                    that.receiveMsgs(msgs);
                })
            }, //监听新消息(大群)事件，必填
            "onMsgNotify": webimhandler.onMsgNotify,//监听新消息(私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息)事件，必填
            "onGroupSystemNotifys": webimhandler.onGroupSystemNotifys, //监听（多终端同步）群系统消息事件，必填
            "onGroupInfoChangeNotify": webimhandler.onGroupInfoChangeNotify//监听群资料变化事件，选填
        };

        //其他对象，选填
        var options = {
            'isAccessFormalEnv': true,//是否访问正式环境，默认访问正式，选填
            'isLogOn': false//是否开启控制台打印日志,默认开启，选填
        };

        if (Config.accountMode == 1) {//托管模式
            webimhandler.sdkLogin(loginInfo, listeners, options, avChatRoomId);
        } else {//独立模式
            //sdk登录
            webimhandler.sdkLogin(loginInfo, listeners, options);
        }
    },

    //跳转到推流页面
    tortmp: function () {
        var id = this.data.live_id;
        wx.createLivePlayerContext('live-player').stop();//关闭
        wx.navigateTo({
            url: '/wxz_superstore/pages/push/push?live_id=' + id
        })
    },
    //聊天接受消息
    receiveMsgs: function (data) {
        var that = this;
        var msgs = this.data.msgs || [];
        var content = data.content;
        var reg = /群提示消息/ig;
        if (reg.test(content)) {
            return;
        }

        var pattern = /data\=(.*?)\,\s+desc\=(.*?)\,\s+ext\=(.*)/i;
        var martchRet = content.match(pattern);

        if (!martchRet) {
            return;
        }
        var ext = martchRet[3];
        ext = JSON.parse(ext);
        var live_id = ext.live_id;
        var nickname = ext.nickname;

        var reg = /系统消息/ig;
        if (reg.test(nickname)) {
            return;
        }

        if (live_id != that.data.live_id) {
            return;
        }

        data.content = martchRet[1];
        data.fromAccountNick = nickname;


        msgs.push(data);
        //最多展示10条信息
        if (msgs.length > 20) {
            msgs.splice(0, msgs.length - 10)
        }
        //过滤掉
        this.setData({
            msgs: msgs,
            'bottom_scroll_top': this.data.bottom_scroll_top + 50,
        })
    },
    initShareData: function () {
        var that = this;
        app.util.request({
            'url': 'setting/get_share',
            'cachetime': '30',
            'data': {'route': app.util.getCurrentPageUrlWithArgs()},
            'showLoading': false,
            success: function (res) {
                var data = res.data.data;
                that.setData({
                    'shareData': data,
                });
            }
        });
    },
    //直播点赞效果
    liveLike: function (e) {
        app.util.request({
            'url': 'live/live_like',
            'data': {'live_id': this.data.live_id},
            'showLoading': false,
            success: function (res) {
            }
        });

        let likeRandom = Math.ceil(10 * Math.random())
        this.setData({
            likeList: [...this.data.likeList, likeRandom]
        })

        // 不支持animation监听 所以只能这样回收
        clearTimeout(this.data.likeTimer)
        this.data.likeTimer = setTimeout(() => {
            if (this.data.likeList.length > 0) {
                this.setData({
                    likeList: []
                })
            }
        }, 2000)
    },
    onShareAppMessage: function (options) {
        //ajax获取分享数据
        var that = this;
        return {
            title: that.data.shareData.title,
            imageUrl: that.data.shareData.imageUrl,
            path: that.data.shareData.path,
            success: function (res) {
                // 转发成功
            },
            fail: function (res) {
                // 转发失败
            }
        }
    },

})
